<?php
/**
 * @Author: king
 * @Last Modified by:   king
 * Date: 2018/10/12
 * Time: 13:27
 */

namespace App\Tools\Astrolog;

use App\Http\Controllers\Api\v1\Astro\DataController;
use App\Http\Controllers\Api\v1\Astro\HousescoreController;
use App\Http\Controllers\Api\v1\Astro\PlanetpowerController;
use App\Exceptions\ApiException;
use Cache;
use DB;
use App\Models\Api\Map as MapRecode;

class Acg
{
    /**
     * @param array $recode
     * @return array
     * @throws \app\common\lib\exception\ApiException
     */
    public function getPlanetInfo($recode = [])
    {
        if (empty($recode)) {
            throw new ApiException('档案信息错误', 200, config('code.error'));
        }

        $timestamp = strtotime($recode['year'] . '-' . $recode['month'] . '-' . $recode['day'] . ' ' . $recode['hour'] . ':' . $recode['minute']);

        $timestamp -= ($recode['timezone'] + $recode['is_summer']) * 3600;

        $utdatenow = strftime("%d.%m.%Y", $timestamp);
        $utnow = strftime("%H:%M:%S", $timestamp);

        $longitude = ($recode['long_deg'] + $recode['long_min'] / 60) * $recode['ew'];
        $latitude = ($recode['lat_deg'] + $recode['lat_min'] / 60) * $recode['ns'];

        $exec_str = config('astrolog.prefix') . " -b{$utdatenow} -ut{$utnow} -p0123456789DAmHt -eswe -house{$longitude},{$latitude},p -fad -g, -head";

        exec($exec_str, $out);

        if (empty($out) || count($out) < 27) {
            unset($out);

            $exec_str = config('astrolog.prefix') . " -b{$utdatenow} -ut{$utnow} -p0123456789DAmHt -eswe -house{$longitude},{$latitude},w -fad -g, -head";

            exec($exec_str, $out);
        }

        $planet1 = [];
        $planet2 = [];
        foreach ($out as $k => $o) {
            if ($k <= 9 || $k == 12 || $k == 27 || $k == 28) {
                $line = explode(',', $o);

                $key = $k;

                if ($k == 27) $key = 17;
                if ($k == 28) $key = 20;

                $planet1[$key] = $line[0] * 1;
                $planet2[$key] = $line[1] * 1;
            }
        }

        return ['planet1' => $planet1, 'planet2' => $planet2];
    }

    public function getPointInfo($info = [])
    {
        $utdatenow = strftime("%d.%m.%Y", $info['time']);
        $utnow = strftime("%H:%M:%S", $info['time']);

        $options_natal = ['utdatenow' => $utdatenow, 'utnow' => $utnow, 'longitude' => $info['longitude'], 'latitude' => $info['latitude'], 'h_sys' => 'p'];
        $options_point = ['utdatenow' => $utdatenow, 'utnow' => $utnow, 'longitude' => $info['point_longitude'], 'latitude' => $info['point_latitude'], 'h_sys' => 'p'];

        $natal_score = $this->getScoreInfo($options_natal);
        $point_score = $this->getScoreInfo($options_point);

        $change = $this->getTheChangeForPoint($natal_score, $point_score, $info['sex']);

        $recommend = $this->recommendScore($natal_score, $point_score, $info['sex']);

        $array = [
            'name' => '石家庄',
            'allowedness' => 50,
            'allowed_color' => '#000000',
            'distance' => '100km',
            'score_list' => $change,
            'explain_list' => [
                0 => [
                    'name' => '桃花之城',
                    'icon' => config('map.fate_city')[2],
                    'description' => '桃花之城描述'
                ],
                1 => [
                    'name' => '幸运之城',
                    'icon' => config('map.fate_city')[2],
                    'description' => '幸运之城描述'
                ],
            ],
            'recommend_list' => $recommend,
            'type' => false
        ];

        return $array;
    }

    /**
     * 获取星盘数据
     * @param array $options
     * @return array
     */
    protected function getScoreInfo($options = [])
    {
        $Data = new DataController();
        $Data->planets_display = '111111111100100011111';
        $Data->asps_display = [0, 60, 90, 120, 180];
        $Data->asp_orb_all = [0 => 8, 60 => 6, 90 => 7, 120 => 7, 180 => 7, 30 => 1, 150 => 2, 45 => 2, 135 => 2, 72 => 2, 144 => 2];
        $Data->planet_orb_all = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];

        $out = $Data->execData($options);

        $original_data = $Data->getOriginalData($out);
        $Data->array_remove($original_data, $Data->planets_display);
        $details = $Data->getPlanetHouseDetail($original_data, $original_data['hc1']);

        $phase = $Data->planetPkPlanet($original_data, $original_data, true);
        foreach ($phase['planets'] as $k => $d) {
            $details['planets'][$k]['phase'] = $d['phase'];
            if (empty($d['phase'])) $details['planets'][$k]['phase'] = null;
        }

        $details['phase'] = $phase['phase'];
        $details['characteristic'] = $Data->recept_or_mutual_recept($details['planets']);

        $details = $Data->get_structure($details);

        $Planetpower = new PlanetpowerController($details);
        $Housescore = new HousescoreController($details);
        $details['planet_score'] = $Planetpower->_initload();
        $details['house_score'] = $Housescore->_initload();

        return $details;
    }

    /**
     * 获取六项变化分数
     * @param array $score1
     * @param array $score2
     * @param int $sex
     * @return array
     */
    protected function getTheChangeForPoint($score1 = [], $score2 = [], $sex = 2)
    {
        $money = $this->getChange(['house' => [2, 8], 'planet' => 3], $score1, $score2);
        $work = $this->getChange(['house' => [6, 10], 'planet' => 0], $score1, $score2);
        $love = $this->getChange(['house' => [5, 7], 'planet' => 3], $score1, $score2);
        if ($sex == 1) $health = $this->getChange(['house' => [1, 6], 'planet' => 0], $score1, $score2);// 男太阳   其他全部取月亮
        else $health = $this->getChange(['house' => [1, 6], 'planet' => 1], $score1, $score2);
        $study = $this->getChange(['house' => [3, 9], 'planet' => 2], $score1, $score2);
        $lucky = $this->getChange(['house' => [5, 9], 'planet' => 5], $score1, $score2);

        $good = '#13d08d';
        $bad = '#ff9400';

        $result = [
            0 => [
                'name' => '财富',
                'percent' => $money >= 0 ? '+' . abs($money) . '%' : $money . '%',
                'color' => $money >= 0 ? $good : $bad,
            ],
            1 => [
                'name' => '工作',
                'percent' => $work >= 0 ? '+' . abs($work) . '%' : $work . '%',
                'color' => $work >= 0 ? $good : $bad,
            ],
            2 => [
                'name' => '婚恋',
                'percent' => $love >= 0 ? '+' . abs($love) . '%' : $love . '%',
                'color' => $love >= 0 ? $good : $bad,
            ],
            3 => [
                'name' => '健康',
                'percent' => $health >= 0 ? '+' . abs($health) . '%' : $health . '%',
                'color' => $health >= 0 ? $good : $bad,
            ],
            4 => [
                'name' => '学习',
                'percent' => $study >= 0 ? '+' . abs($study) . '%' : $study . '%',
                'color' => $study >= 0 ? $good : $bad,
            ],
            5 => [
                'name' => '幸运',
                'percent' => $lucky >= 0 ? '+' . abs($lucky) . '%' : $lucky . '%',
                'color' => $lucky >= 0 ? $good : $bad,
            ],
        ];

        return $result;
    }

    /**
     * 获取重置盘与本命盘之间 各项指数的变化
     * @param array $options
     * @param array $or_data
     * @param array $new_data
     * @param bool $is_fate
     * @return float|int
     */
    protected function getChange($options = [], $or_data = [], $new_data = [], $is_fate = false)
    {
        $house_chage = 0;

        foreach ($options['house'] as $h) {
            $house_chage += $this->changeByHouse($h, $or_data, $new_data);
        }

        $planet_chage = $this->changeByPlanet($options['planet'], $or_data, $new_data);

        $result = $house_chage + $planet_chage;

        if ($result == 0) $result = 0;// -0 = 0

        return $is_fate ? $result : round($result);
    }

    /**
     * 宫位分数变化
     * @param int $house
     * @param array $or_data
     * @param array $new_data
     * @param bool $is_fate
     * @return float|int
     */
    protected function changeByHouse($house = 1, $or_data = [], $new_data = [], $is_fate = false)
    {
        $or_house = $or_data['house_score'][$house - 1]['lucky'] - $or_data['house_score'][$house - 1]['burn'];
        $new_house = $new_data['house_score'][$house - 1]['lucky'] - $new_data['house_score'][$house - 1]['burn'];

        if ($is_fate === false) {
            $house_chage = ($new_house - $or_house) / 40;

            if ($house_chage > 20) $house_chage = 20;
        } else {
            $house_chage = ($new_house - $or_house) / 500;
        }

        return $house_chage;
    }

    /**
     * 行星合轴提升、角距影响
     * @param int $planet
     * @param array $or_data
     * @param array $new_data
     * @return float|int
     */
    protected function changeByPlanet($planet = 0, $or_data = [], $new_data = [])
    {
        $cacl_base = 60;
        $base_orb = 15;

        $or_planet_axis = 0;// 合轴提升
        $new_planet_axis = 0;// 合轴提升

        $or_phase = $or_data['planets'][$planet]['phase'];
        $new_phase = $new_data['planets'][$planet]['phase'];

        if (isset($new_phase[$planet . '-' . ASC]) && $new_phase[$planet . '-' . ASC]['phase_e'] == 0) {
            $phase_orb = $new_phase[$planet . '-' . ASC]['phase_orb'];
            $ch = (1 - $phase_orb / $base_orb) * $cacl_base;
            if ($ch > $cacl_base) $ch = $cacl_base;
            $new_planet_axis += $ch;
        }
        if (isset($new_phase[$planet . '-' . IC]) && $new_phase[$planet . '-' . IC]['phase_e'] == 0) {
            $phase_orb = $new_phase[$planet . '-' . IC]['phase_orb'];
            $ch = (1 - $phase_orb / $base_orb) * $cacl_base;
            if ($ch > $cacl_base) $ch = $cacl_base;
            $new_planet_axis += $ch;
        }
        if (isset($new_phase[$planet . '-' . DES]) && $new_phase[$planet . '-' . DES]['phase_e'] == 0) {
            $phase_orb = $new_phase[$planet . '-' . DES]['phase_orb'];
            $ch = (1 - $phase_orb / $base_orb) * $cacl_base;
            if ($ch > $cacl_base) $ch = $cacl_base;
            $new_planet_axis += $ch;
        }
        if (isset($new_phase[$planet . '-' . MC]) && $new_phase[$planet . '-' . MC]['phase_e'] == 0) {
            $phase_orb = $new_phase[$planet . '-' . MC]['phase_orb'];
            $ch = (1 - $phase_orb / $base_orb) * $cacl_base;
            if ($ch > $cacl_base) $ch = $cacl_base;
            $new_planet_axis += $ch;
        }
        if (isset($or_phase[$planet . '-' . ASC]) && $or_phase[$planet . '-' . ASC]['phase_e'] == 0) {
            $phase_orb = $or_phase[$planet . '-' . ASC]['phase_orb'];
            $ch = (1 - $phase_orb / $base_orb) * $cacl_base;
            if ($ch > $cacl_base) $ch = $cacl_base;
            $or_planet_axis += $ch;
        }
        if (isset($or_phase[$planet . '-' . IC]) && $or_phase[$planet . '-' . IC]['phase_e'] == 0) {
            $phase_orb = $or_phase[$planet . '-' . IC]['phase_orb'];
            $ch = (1 - $phase_orb / $base_orb) * $cacl_base;
            if ($ch > $cacl_base) $ch = $cacl_base;
            $or_planet_axis += $ch;
        }
        if (isset($or_phase[$planet . '-' . DES]) && $or_phase[$planet . '-' . DES]['phase_e'] == 0) {
            $phase_orb = $or_phase[$planet . '-' . DES]['phase_orb'];
            $ch = (1 - $phase_orb / $base_orb) * $cacl_base;
            if ($ch > $cacl_base) $ch = $cacl_base;
            $or_planet_axis += $ch;
        }
        if (isset($or_phase[$planet . '-' . MC]) && $or_phase[$planet . '-' . MC]['phase_e'] == 0) {
            $phase_orb = $or_phase[$planet . '-' . MC]['phase_orb'];
            $ch = (1 - $phase_orb / $base_orb) * $cacl_base;
            if ($ch > $cacl_base) $ch = $cacl_base;
            $or_planet_axis += $ch;
        }

        if ($or_planet_axis == 0) {
            if ($new_planet_axis != 0) {
                $result = $new_planet_axis;
            } // 若都不合轴，则取角宫距离影响
            else {
                $or_planet_in_house = $or_data['planets'][$planet]['in_house_id'];
                $new_planet_in_house = $new_data['planets'][$planet]['in_house_id'];

                $regular = [
                    1 => 1, 2 => 1, 3 => 1,
                    4 => 4, 5 => 4, 6 => 4,
                    7 => 7, 8 => 7, 9 => 7,
                    10 => 10, 11 => 10, 12 => 10,
                ];

                $or_axis_distance = abs($or_data['planets'][$planet]['deg'] - $or_data['houses'][$regular[$or_planet_in_house]]['deg']);
                if ($or_axis_distance > 180) $or_axis_distance = 360 - $or_axis_distance;

                $new_axis_distance = abs($new_data['planets'][$planet]['deg'] - $new_data['houses'][$regular[$new_planet_in_house]]['deg']);
                if ($new_axis_distance > 180) $new_axis_distance = 360 - $new_axis_distance;

                $planet_distance = ($new_axis_distance - $or_axis_distance) / 6;// 角距影响
                if ($planet_distance > 20) $planet_distance = 20;

                $result = -($planet_distance);
            }
        } else $result = ($new_planet_axis - $or_planet_axis) / $or_planet_axis * $cacl_base + 40;

        return $result;
    }

    /**
     * 位置推荐指数
     * @param array $or_data
     * @param array $new_data
     * @param int $sex
     * @param bool $is_fate
     * @return array
     */
    protected function recommendScore($or_data = [], $new_data = [], $sex = 2, $is_fate = false)
    {
        $result = [
            0 => [
                'name' => '养生',
                'score' => 0,
                'status' => '不适宜',
                'icon' => config('map.map')['yangcheng_recommend']
            ],
            1 => [
                'name' => '工作',
                'score' => 0,
                'status' => '不适宜',
                'icon' => config('map.map')['work_recommend']
            ],
            2 => [
                'name' => '学习',
                'score' => 0,
                'status' => '不适宜',
                'icon' => config('map.map')['study_recommend']
            ],
            3 => [
                'name' => '旅游',
                'score' => 0,
                'status' => '不适宜',
                'icon' => config('map.map')['trip_recommend']
            ],
            4 => [
                'name' => '定居',
                'score' => 0,
                'status' => '不适宜',
                'icon' => config('map.map')['dingju_recommend']
            ],
            5 => [
                'name' => '婚恋',
                'score' => 0,
                'status' => '不适宜',
                'icon' => config('map.map')['love_recommend']
            ],
            6 => [
                'name' => '财富',
                'score' => 0,
                'status' => '不适宜',
                'icon' => ''
            ],
            7 => [
                'name' => '社交',
                'score' => 0,
                'status' => '不适宜',
                'icon' => ''
            ]
        ];
        // 0养生 1工作 2学习 3旅游 4定居 5婚恋 6财富 7社交
        for ($i = 0; $i < 6; $i++) {
            if ($i == 4) continue;

            $planet = $new_data['planets'][$i];

            $new_phase = $planet['phase'];

            $is_asc = $is_ic = $is_des = $is_mc = false;

            $cacl_base = 15;
            $ch = 0;

            if (isset($new_phase[$i . '-' . ASC]) && $new_phase[$i . '-' . ASC]['phase_e'] == 0) {
                $ch = (1 - $new_phase[$i . '-' . ASC]['phase_orb'] / $cacl_base);
                $is_asc = true;
            } elseif (isset($new_phase[$i . '-' . DES]) && $new_phase[$i . '-' . DES]['phase_e'] == 0) {
                $ch = (1 - $new_phase[$i . '-' . DES]['phase_orb'] / $cacl_base);
                $is_des = true;
            } elseif (isset($new_phase[$i . '-' . MC]) && $new_phase[$i . '-' . MC]['phase_e'] == 0) {
                $ch = (1 - $new_phase[$i . '-' . MC]['phase_orb'] / $cacl_base);
                $is_mc = true;
            } elseif (isset($new_phase[$i . '-' . IC]) && $new_phase[$i . '-' . IC]['phase_e'] == 0) {
                $ch = (1 - $new_phase[$i . '-' . IC]['phase_orb'] / $cacl_base);
                $is_ic = true;
            }


            if ($is_asc || $is_ic || $is_des || $is_mc) {

                $cond = false;
                if (!empty($new_phase)) {
                    $is_phase90180 = false;
                    foreach ($new_phase as $np) {
                        if (in_array($np['phase_e'], [90, 180])) $is_phase90180 = true;
                        if (in_array($np['id'], [3, 5])) $cond = true;
                    }
                    if (!$is_phase90180) $cond = true;
                }

                // 0养生 1工作 2学习 3旅游 4定居 5婚恋 6财富 7社交
                // 太阳
                if ($i == 0) {
                    if ($sex == 1) $result[0]['score'] += $ch;// 男 养生
                    else $result[5]['score'] += $ch;// 女 恋爱
                    $result[1]['score'] += $ch;// 工作
                    if ($is_ic && $cond) $result[4]['score'] += $ch;// 定居-天底 且太阳有金木相位或无刑冲
                    if ($is_des) $result[5]['score'] += $ch;// 恋爱-下降
                } // 月亮
                elseif ($i == 1) {
                    $result[4]['score'] += $ch;//   定居
                    if ($sex == 1) $result[5]['score'] += $ch;//    恋爱（男）
                    else $result[0]['score'] += $ch;//  养生（女）
                    if ($is_mc && $cond) $result[1]['score'] += $ch;//  工作-天顶 且月亮有金木相位或无刑冲
                    if ($is_des && $cond) $result[5]['score'] += $ch;// 恋爱-下降 且月亮有金木相位或无刑冲
                } // 水星
                elseif ($i == 2) {
                    $result[3]['score'] += $ch;//   旅游
                    $result[2]['score'] += $ch;//   学习
                    if ($is_mc && $cond) $result[1]['score'] += $ch;//  工作-天顶 且水星有金木相位或无刑冲
                    if ($is_ic && $cond) $result[4]['score'] += $ch;//  定居-天底 且水星有金木相位或无刑冲
                    if ($is_des && $cond) $result[5]['score'] += $ch;// 恋爱-下降 且水星有金木相位或无刑冲
                } // 金星
                elseif ($i == 3) {
                    $result[5]['score'] += $ch;//   恋爱
                    $result[3]['score'] += $ch;//   旅游
                    $result[6]['score'] += $ch;//   财富
                    $result[7]['score'] += $ch;//   社交
                    if ($is_mc && $cond) $result[1]['score'] += $ch;//  工作-天顶
                    if ($is_mc && $cond) $result[4]['score'] += $ch;//  定居-天底
                } // 木星
                elseif ($i == 5) {
                    $result[3]['score'] += $ch;//   旅游
                    $result[2]['score'] += $ch;//   学习
                    if ($is_mc && $cond) $result[1]['score'] += $ch;//  工作-天顶
                    if ($is_ic && $cond) $result[4]['score'] += $ch;//  定居-天底
                    if ($is_des && $cond) $result[5]['score'] += $ch;// 恋爱-下降
                }
            }
        }
        // 0养生 1工作 2学习 3旅游 4定居 5婚恋 6财富 7社交
        for ($j = 1; $j < 13; $j++) {
            $house = $this->changeByHouse($j, $or_data, $new_data);

            if ($j == 1) {
                $result[0]['score'] += $house;
            } elseif ($j == 2) {
                $result[1]['score'] += $house;
                $result[6]['score'] += $house;
            } elseif ($j == 3) {
                $result[2]['score'] += $house;
                $result[3]['score'] += $house;
            } elseif ($j == 4) {
                $result[4]['score'] += $house;
            } elseif ($j == 5) {
                $result[5]['score'] += $house;
            } elseif ($j == 6) {
                $result[0]['score'] += $house;
                $result[1]['score'] += $house;
            } elseif ($j == 7) {
                $result[5]['score'] += $house;
                $result[7]['score'] += $house;
            } elseif ($j == 8) {
                $result[0]['score'] += $house;
                $result[6]['score'] += $house;
            } elseif ($j == 9) {
                $result[2]['score'] += $house;
                $result[3]['score'] += $house;
            } elseif ($j == 10) {
                $result[1]['score'] += $house;
            } elseif ($j == 11) {
                $result[3]['score'] += $house;
                $result[5]['score'] += $house;
                $result[7]['score'] += $house;
            } elseif ($j == 12) {
                $result[0]['score'] += $house;
            }
        }

        if ($is_fate === false) {
            unset($result[6]);
            unset($result[7]);
        }

        $result = resort($result, 'score');

        $temp = [];

        foreach ($result as $k => $re) {
            if ($re['score'] <= 0) {
                $result[$k]['score'] = 0;
                $result[$k]['status'] = '不适宜';
            } else {
                if ($is_fate === false) {
                    $result[$k]['score'] = round($re['score'] * 100);

                    if ($result[$k]['score'] > 100) $result[$k]['score'] = 100;
                }

                if ($result[$k]['score'] < 20) $result[$k]['status'] = '适宜';

                elseif ($result[$k]['score'] < 40) $result[$k]['status'] = '较好';

                elseif ($result[$k]['score'] < 60) $result[$k]['status'] = '良好';

                elseif ($result[$k]['score'] < 80) $result[$k]['status'] = '力荐';

                else $result[$k]['status'] = '绝佳';

            }
            $temp[$k] = $result[$k]['score'];
        }
        if ($is_fate !== false) return $temp;
        else return $result;
    }

    /**
     * 获取当前档案的命运之城列表 入库+缓存
     * 0养生=颐养之城
     * 1工作=成功之城
     * 2学习=知识之城
     * 3旅游=游乐之城
     * 4定居=安居之城
     * 5婚恋=桃花之城
     * 6=财富之城
     * 7=社交之城
     * 8幸运=幸运之城
     * @param array $info
     * @return array
     */
    public function getFateCityOld($info = [])
    {
        $utdatenow = strftime("%d.%m.%Y", $info['time']);
        $utnow = strftime("%H:%M:%S", $info['time']);

        $longitude = $info['longitude'];
        $latitude = $info['latitude'];

        $options_natal = ['utdatenow' => $utdatenow, 'utnow' => $utnow, 'longitude' => $longitude, 'latitude' => $latitude, 'h_sys' => 'p'];

        $natal_score = $this->getScoreInfo($options_natal);

        $citys = config('city.lon_lat');// 经纬度
//        $names = config('city.name');// 城市名

        $temp = [];
        if (!empty($citys)) {
            foreach ($citys as $k => $city) {
                $longitude_point = $city[0];
                $latitude_point = $city[1];

                $options_point = ['utdatenow' => $utdatenow, 'utnow' => $utnow, 'longitude' => $longitude_point, 'latitude' => $latitude_point, 'h_sys' => 'p'];

                $point_score = $this->getScoreInfo($options_point);

                $scores = $this->recommendScore($natal_score, $point_score, $info['sex'], true);

                $lucky = $this->getChange(['house' => [5, 9], 'planet' => 5], $natal_score, $point_score, true);

                if ($lucky <= 0) $lucky = 0;

                $scores[] = $lucky;
                $temp[$k] = $scores;
            }
        }

        $list = [];
        foreach ($temp as $i => $c) {
            foreach ($c as $j => $s) $list[$j][$i] = $s;
        }

        $result = [];
        $fate_city = config('map.fate_city');
        $fate_city_loc = config('map.fate_city_loc');
        $fate_city_des = config('map.fate_city_title');// 命运之城提示窗信息
        // 这座城市对你来说可谓祥云笼罩，大吉大利，分别是你的[city]。想知道它会给你带来哪些具体好处，可点击进入城市详情页面查看。
        // 显示效果：
        // 这座城市对你来说可谓祥云笼罩，大吉大利，分别是你的桃花之城、命运之城、宿命之城等3个命运之城。想知道它会给你带来哪些具体好处，可点击进入城市详情页面查看。

        $fates = [];


        foreach ($list as $fate => $l) {
            $max = max($l);

            if ($max <= 0) continue;

            $fate_name = config('map.fate_city_name')[$fate];
            foreach ($l as $key => $m) {
                // 获取最大值城市 key
                if ($m == $max) {
//                    $name = $names[$key];// 命运之城城市名
                    $lon_lat = $citys[$key];// 命运之城城市经纬度
                    if (isset($result[$key]['name'])) {
                        // 当前城市属于多个命运之城
                        $result[$key]['name'] .= '、' . $fate_name;
                        $result[$key]['icon'] = $fate_city[10];
                        $result[$key]['loc_icon'] = $fate_city_loc[10];
                        $result[$key]['description'] = $fate_city_des[10];
                    } else {
                        // 第一条
                        $result[$key] = [
                            'icon' => $fate_city[$fate],
                            'loc_icon' => $fate_city_loc[$fate],
//                            'name' => $name . ':' . $fate_name,
                            'name' => $fate_name,
                            'description' => $fate_city_des[$fate],
                            'longitude' => $lon_lat[0],
                            'latitude' => $lon_lat[1]
                        ];
                    }
                    $fates[] = [
                        'id' => $fate,
                        'uid' => $info['uid'],
                        'rid' => $info['rid'],
                        'longitude' => $lon_lat[0],
                        'latitude' => $lon_lat[1]
                    ];
                }
            }
        }
        foreach ($result as $k => $r) {
            if (mb_strlen($r['name']) > 4) {
                $fate_city_count = count(explode('、', $r['name']));

                $result[$k]['description'] = str_replace('[city]', $r['name'] . '等' . $fate_city_count . '个命运之城', $r['description']);
            }
        }
        $result = array_values($result);

        Cache::set('fate_city_' . $info['rid'], $result, 86400 * 7);

        $this->saveFateCity($fates);

        return $result;
    }

    /**
     * @param array $fates
     */
    protected function saveFateCity($fates = [])
    {
        if (!empty($fates)) {
            $rid = null;
            $inserts = [];
            // 命运之城城市经纬度已内置入库
            $citys = config('city.lon_lat');// 经纬度

            foreach ($fates as $f) {
                foreach ($citys as $i => $c) {
                    if ($f['longitude'] == $c[0] && $f['latitude'] == $c[1]) {
                        if ($rid === null) $rid = $f['rid'];

                        $inserts[] = ['mid' => $i + 1, 'fcid' => $f['id'], 'uid' => $f['uid'], 'rid' => $f['rid']];
                    }
                }
            }
            if (!empty($inserts)) {
                try {
                    // 先删除当前档案的命运之城
                    DB::table('wechat.app_fate_city_user')->where('rid', $rid)->delete();

                    DB::table('wechat.app_fate_city_user')->insertAll($inserts);

                } catch (\Exception $e) {

                }
            }
        }
    }

    /**
     * @param array $info
     * @return array|bool|mixed
     * @throws ApiException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getFateCity($info = [])
    {
        $result = Cache::get('fate_city_' . $info['rid']);

        if ($result === false || empty($result)) {
            $fate_city = config('map.fate_city');
            $fate_city_name = config('map.fate_city_name');
            $fate_city_loc = config('map.fate_city_loc');
            $fate_city_des = config('map.fate_city_title');// 命运之城提示窗信息

            // 当前无缓存，先查库（是否计算过）
            try {
                $data = DB::table('wechat.app_fate_city_user')
                    ->alias('fcu')
                    ->join('wechat.app_map m', 'fcu.mid=m.id', 'LEFT')
                    ->field('fcu.fcid,m.id,m.longitude,m.latitude')
                    ->where(['uid' => $info['uid'], 'rid' => $info['rid']])
                    ->selectOrFail();
                $result = [];
                foreach ($data as $d) {
                    // key 为经纬度id 即城市id
                    if (isset($result[$d['id']]['name'])) {
                        $result[$d['id']]['name'] .= '、' . $fate_city_name[$d['fcid']];
                        $strlen = mb_strlen($result[$d['id']]['name']);
                        if ($strlen == 9) {
                            $result[$d['id']]['icon'] = $fate_city[10];
                            $result[$d['id']]['loc_icon'] = $fate_city_loc[10];
                            $result[$d['id']]['description'] = $fate_city_des[10];
                        }
                    } else {
                        $result[$d['id']]['name'] = $fate_city_name[$d['fcid']];
                        $result[$d['id']]['icon'] = $fate_city[$d['fcid']];
                        $result[$d['id']]['loc_icon'] = $fate_city_loc[$d['fcid']];
                        $result[$d['id']]['description'] = $fate_city_des[$d['fcid']];
                        $result[$d['id']]['longitude'] = $d['longitude'];
                        $result[$d['id']]['latitude'] = $d['latitude'];
                    }
                }
                foreach ($result as $k => $r) {
                    if (mb_strlen($r['name']) > 4) {
                        $fate_city_count = count(explode('、', $r['name']));

                        $result[$k]['description'] = str_replace('[city]', $r['name'] . '等' . $fate_city_count . '个命运之城', $r['description']);
                    }
                }
                $result = array_values($result);

                Cache::set('fate_city_' . $info['rid'], $result, 86400 * 3);

                // 首次运算命运之城数据，计算后入库
            } catch (\Exception $e) {

                $citys = config('city.lon_lat');// 经纬度
                $info['fate'] = true;
                $score = [];
                if (!empty($citys)) {
                    foreach ($citys as $k => $city) {
                        $info['point_longitude'] = $city[0];
                        $info['point_latitude'] = $city[1];
                        $score[$k] = $this->getRecommendedInfo($info);
                    }
                }

                $list = $result = $fates = [];
                foreach ($score as $i => $c) foreach ($c as $j => $s) $list[$j][$i] = $s;

                foreach ($list as $fate => $l) {
                    $max = max($l);

                    if ($max <= 0) continue;

                    $fate_name = $fate_city_name[$fate];
                    foreach ($l as $key => $m) {
                        // 获取最大值城市 key
                        if ($m == $max) {
                            $lon_lat = $citys[$key];// 命运之城城市经纬度
                            if (isset($result[$key]['name'])) {
                                // 当前城市属于多个命运之城
                                $result[$key]['name'] .= '、' . $fate_name;
                                $result[$key]['icon'] = $fate_city[10];
                                $result[$key]['loc_icon'] = $fate_city_loc[10];
                                $result[$key]['description'] = $fate_city_des[10];
                            } else {
                                // 第一条
                                $result[$key] = [
                                    'icon' => $fate_city[$fate],
                                    'loc_icon' => $fate_city_loc[$fate],
                                    'name' => $fate_name,
                                    'description' => $fate_city_des[$fate],
                                    'longitude' => $lon_lat[0],
                                    'latitude' => $lon_lat[1]
                                ];
                            }
                            $fates[] = [
                                'id' => $fate,
                                'uid' => $info['uid'],
                                'rid' => $info['rid'],
                                'longitude' => $lon_lat[0],
                                'latitude' => $lon_lat[1]
                            ];
                        }
                    }
                }
                foreach ($result as $k => $r) {
                    if (mb_strlen($r['name']) > 4) {
                        $fate_city_count = count(explode('、', $r['name']));

                        $result[$k]['description'] = str_replace('[city]', $r['name'] . '等' . $fate_city_count . '个命运之城', $r['description']);
                    }
                }
                $result = array_values($result);

                // 保存命运之城入库
                $this->saveFateCity($fates);
            }
        }
        return $result;
    }

    /**
     * 计算当前经纬度的各项加分项
     * @param array $info
     * fate true 命运之城计算，返回数值
     * type 2 命运之城详情 需要返回命运之城解释说明
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws ApiException
     */
    public function getRecommendedInfo($info = [])
    {
        $utdatenow = strftime("%d.%m.%Y", $info['time']);
        $utnow = strftime("%H:%M:%S", $info['time']);

        $options = ['utdatenow' => $utdatenow, 'utnow' => $utnow, 'longitude' => $info['point_longitude'], 'latitude' => $info['point_latitude'], 'h_sys' => 'p'];

        $data = $this->getScoreInfo($options);

        $money = $work = $study = $health = $love = $lucky = $travle = $home = $chat = 0;

        // 计算各星影响力
        $p = [
            0 => $this->getPlanetInfluence(0, $data),
            1 => $this->getPlanetInfluence(1, $data),
            2 => $this->getPlanetInfluence(2, $data),
            3 => $this->getPlanetInfluence(3, $data),
            4 => $this->getPlanetInfluence(4, $data),
            5 => $this->getPlanetInfluence(5, $data),
            6 => $this->getPlanetInfluence(6, $data),
            7 => $this->getPlanetInfluence(7, $data),
            8 => $this->getPlanetInfluence(8, $data),
            9 => $this->getPlanetInfluence(9, $data),
            12 => $this->getPlanetInfluence(12, $data),
            16 => $this->getPlanetInfluence(16, $data)
        ];
        // 计算宫位吉凶
        $h = [
            1 => $this->changeByHousePower(1, $data),
            2 => $this->changeByHousePower(2, $data),
            3 => $this->changeByHousePower(3, $data),
            4 => $this->changeByHousePower(4, $data),
            5 => $this->changeByHousePower(5, $data),
            6 => $this->changeByHousePower(6, $data),
            7 => $this->changeByHousePower(7, $data),
            8 => $this->changeByHousePower(8, $data),
            9 => $this->changeByHousePower(9, $data),
            10 => $this->changeByHousePower(10, $data),
            11 => $this->changeByHousePower(11, $data),
            12 => $this->changeByHousePower(12, $data),
        ];
        // 计算宫主星影响
        $hp = [
            2 => $p[$data['houses'][2]['protect_id']],
            3 => $p[$data['houses'][3]['protect_id']],
            8 => $p[$data['houses'][8]['protect_id']],
            9 => $p[$data['houses'][9]['protect_id']],
        ];

        $money += $p[5] * 0.8;
        $money += $p[3];
        $money += $hp[2];
        $money += $hp[8];
        $money += $h[2] / 10;
        $money += $h[8] / 20;

        for ($i = 0; $i < ASC; $i++) {
            if (!isset($data['planets'][$i])) continue;

            $planetPhase = $data['planets'][$i]['phase'];

            if (isset($planetPhase[$i . '-' . MC]) && $planetPhase[$i . '-' . MC]['phase_e'] == 0) {
                if ($i == 0 || $i == 5) $work += 80;
                elseif ($i == 3) $work += 70;
                elseif ($i == 2 || $i == 1) $work += 40;
                elseif ($i == 4) {
                    $has_phase_90180 = false;

                    foreach ($planetPhase as $phase) if (in_array($phase['phase_e'], [90, 180])) $has_phase_90180 = true;

                    if ($has_phase_90180 === false) $work += 20;

                    else $work -= 30;
                } elseif ($i == 6) {
                    $has_phase_90180 = false;

                    foreach ($planetPhase as $phase) if (in_array($phase['phase_e'], [90, 180])) $has_phase_90180 = true;

                    if ($has_phase_90180 === false) $work += 40;

                    else $work -= 30;
                } elseif ($i == 7) {
                    $has_phase_90180 = false;

                    foreach ($planetPhase as $phase) if (in_array($phase['phase_e'], [90, 180])) $has_phase_90180 = true;

                    if ($has_phase_90180 === false) $work += 30;

                    else $work -= 30;
                } elseif ($i == 8) {
                    $has_phase_90180 = false;

                    foreach ($planetPhase as $phase) if (in_array($phase['phase_e'], [90, 180])) $has_phase_90180 = true;

                    if ($has_phase_90180 === false) $work += 10;

                    else $work -= 50;
                } elseif ($i == 9) {
                    $has_phase_90180 = false;

                    foreach ($planetPhase as $phase) if (in_array($phase['phase_e'], [90, 180])) $has_phase_90180 = true;

                    if ($has_phase_90180 === false) $work += 15;

                    else $work -= 50;
                } elseif ($i == 12) $work += 70;
                elseif ($i == 16) $work -= 30;
            }
        }
        $work += $p[5] * 0.5;
        $work += $p[0] * 0.5;
        $work += $p[3] * 0.5;
        $work -= $p[4] * 0.2;
        $work -= $p[6] * 0.2;
        $work -= $p[7] * 0.2;
        $work -= $p[8] * 0.2;
        $work -= $p[9] * 0.2;
        $work += $h[10] / 10;
        $work += $h[6] / 25;

        $study += $p[2];
        $study += $p[5] * 0.8;
        $study += $p[7] * 0.4;
        $study += $hp[3] * 0.4;
        $study += $hp[9] * 0.2;
        $study += $h[3] / 15;
        $study += $h[9] / 20;

        $health -= $p[4] * 0.4;
        $health -= $p[6] * 0.4;
        $health -= $p[7] * 0.4;
        $health -= $p[9] * 0.4;
        $health += $p[0] * 0.5;
        $health += $p[5] * 0.4;
        $health += $p[3] * 0.3;
        $health += $p[1] * 0.3;
        for ($i = 0; $i < 10; $i++) {
            $change = [40, 20, 0, 25, -30, 25, -30, -15, -30, -30];

            $planetPhase = $data['planets'][$i]['phase'];

            if (isset($planetPhase[$i . '-' . ASC]) && $planetPhase[$i . '-' . ASC]['phase_e'] == 0) {
                $health += $change[$i];
            }
        }

        $love -= $p[7] * 0.4;
        $love -= $p[8] * 0.4;
        $love -= $p[9] * 0.4;
        $love -= $p[6] * 0.2;
        $love += $p[3];
        $love += $p[5] * 0.2;
        $love += $h[7] / 15;
        $love += $h[5] / 15;
        for ($i = 0; $i < 10; $i++) {
            if ($info['sex'] == 1) $change = [20, 30, 0, 30, -20, 15, -10, -30, -30, -30];
            else $change = [30, 20, 0, 30, -20, 15, -10, -30, -30, -30];

            $planetPhase = $data['planets'][$i]['phase'];

            if (isset($planetPhase[$i . '-' . DES]) && $planetPhase[$i . '-' . DES]['phase_e'] == 0) {
                $love += $change[$i];
            }
        }

        $lucky += $p[5];
        $lucky += $p[3] * 0.3;
        $lucky += $p[0] * 0.2;
        $lucky += $p[7] * 0.1;
        $lucky -= $p[4] * 0.5;
        $lucky -= $p[6] * 0.5;
        $lucky -= $p[8] * 0.5;
        $lucky -= $p[9] * 0.5;
        $lucky += max([$h[1], $h[4], $h[7], $h[10], $h[5], $h[9], $h[11]]) / 10;

        $travle += $p[5];
        $travle += $p[3] * 0.5;
        $travle += $p[0] * 0.3;
        $travle += $p[2] * 0.5;
        $travle -= $p[4] * 0.5;
        $travle -= $p[6] * 0.5;
        $travle -= $p[8] * 0.5;
        $travle -= $p[9] * 0.5;
        $travle += $h[3] / 20;
        $travle += $h[9] / 15;

        $home += ($money + $work + $health + $love) / 5;
        $home += $p[1];
        $home += $h[4] / 15;
        $home = ($home / 3);
        if ($home > 100) $home = 10;

        $chat -= $p[4] * 0.3;
        $chat -= $p[6] * 0.3;
        $chat -= $p[7] * 0.3;
        $chat -= $p[8] * 0.3;
        $chat -= $p[9] * 0.3;
        $chat += $p[3] * 1.5;
        $chat += $p[5] * 0.5;
        $chat += $p[2] * 0.4;
        $chat += $h[7] / 15;
        $chat += $h[11] / 15;
        for ($i = 0; $i < 10; $i++) {
            $change = [30, 30, 30, 40, -30, 30, -30, -30, -30, -30];

            $planetPhase = $data['planets'][$i]['phase'];

            if (isset($planetPhase[$i . '-' . DES]) && $planetPhase[$i . '-' . DES]['phase_e'] == 0) {
                $chat += $change[$i];
            }
        }

        // 开始计算命格线的影响，获取当前点与所有命格线的经度差
        $longitude_diff = $this->getDrawLineInfo($info);

        $multiple = 1;// 在最强能量点范围的倍数

        $influ = [];// 在某些线条的影响范围内

        if (!empty($longitude_diff)) {

            foreach ($longitude_diff as $i => $ld) {

                if ($i === 'near_power') {
                    $multiple = $ld;
                    continue;
                }

                if ($ld[0] < 1) {

                    $ratio = (1 - $ld[0]) / 2;

                    if ($i == 0) {
                        $work += 80 * $ratio;
                        if ($info['sex'] != 1) $love += 50 * $ratio;
                        $lucky += 40 * $ratio;
//                        $money += 0;
//                        $study += 0 ;
                        $health += 80 * $ratio;
//                        $home += 0 ;
                        $travle += 10 * $ratio;
                        $chat += 20;
                    } elseif ($i == 1) {
//                        $work += 0;
                        if ($info['sex'] == 1) $love += 50 * $ratio;
//                        $lucky += 0;
                        $money += 30 * $ratio;
//                        $study += 0;
//                        $health += 0;
                        $home += 70 * $ratio;
//                        $travle += 0;
                        $chat += 10 * $ratio;
                    } elseif ($i == 2) {
//                        $work += 0;
//                        if ($info['sex'] != 1) $love += 0;
//                        $lucky += 0;
//                        $money += 0;
                        $study += 120 * $ratio;
//                        $health += 0;
//                        $home += 0;
                        $travle += 60 * $ratio;
                        $chat += 30 * $ratio;
                    } elseif ($i == 3) {
//                        $work += 0;
                        $love += 100 * $ratio;
                        $lucky += 30 * $ratio;
                        $money += 90 * $ratio;
//                        $study += 0;
//                        $health += 0;
//                        $home += 0;
                        $travle += 50 * $ratio;
                        $chat += 100 * $ratio;
                    } elseif ($i == 4) {
//                        $work += 0;
                        if ($info['sex'] != 1) $love += 30 * $ratio;
                        $lucky -= 40 * $ratio;
//                        $money += 0;
//                        $study += 0;
                        $health -= 30 * $ratio;
//                        $home += 0;
                        $travle -= 30 * $ratio;
                        $chat -= 20 * $ratio;
                    } elseif ($i == 5) {
                        $work += 80 * $ratio;
//                        $love += 0;
                        $lucky += 120 * $ratio;
                        $money += 50 * $ratio;
                        $study += 60 * $ratio;
//                        $health += 0;
//                        $home += 0;
                        $travle += 100 * $ratio;
//                        $chat += 0;
                    } elseif ($i == 6) {
//                        $work += 0;
//                        if ($info['sex'] != 1) $love += 0;
                        $lucky -= 40 * $ratio;
//                        $money += 0;
//                        $study += 0;
                        $health -= 30 * $ratio;
//                        $home += 0;
                        $travle -= 30 * $ratio;
                        $chat -= 20 * $ratio;
                    } elseif ($i == 7) {
//                        $work += 0;
                        $love -= 70 * $ratio;
//                        $lucky += 0;
//                        $money += 0;
                        $study += 30 * $ratio;
//                        $health += 0;
                        $home -= 30 * $ratio;
                        $travle -= 20 * $ratio;
//                        $chat += 0;
                    } elseif ($i == 8) {
//                        $work += 0;
//                        $love += 0;
                        $lucky -= 40 * $ratio;
//                        $money += 0;
//                        $study += 0;
                        $health -= 30 * $ratio;
//                        $home += 0;
                        $travle -= 30 * $ratio;
                        $chat -= 20 * $ratio;
                    } elseif ($i == 9) {
//                        $work += 0;
//                        $love += 0;
                        $lucky -= 40 * $ratio;
//                        $money += 0;
//                        $study += 0;
                        $health -= 30 * $ratio;
//                        $home += 0;
                        $travle -= 30 * $ratio;
                        $chat -= 20 * $ratio;
                    } elseif ($i == 12) {
                        $work += 50 * $ratio;
                        $love -= 20 * $ratio;
                        $lucky += 30 * $ratio;
                        $money += 30 * $ratio;
//                        $study += 0;
                        $health += 30 * $ratio;
//                        $home += 0;
//                        $travle += 0;
                        $chat -= 20 * $ratio;
                    }

                    $influ[$i][0] = $ratio;
                }

                if ($ld[1] < 1) {

                    $ratio = (1 - $ld[1]) / 2;

                    if ($i == 0) {
                        $work += 120 * $ratio;
                        if ($info['sex'] != 1) $love += 30 * $ratio;
                        $lucky += 60 * $ratio;
//                        $money += 0;
                        $study += 30 * $ratio;
                        $health += 30 * $ratio;
//                        $home += 0;
                        $travle += 20 * $ratio;
                        $chat += 20 * $ratio;
                    } elseif ($i == 1) {
                        $work += 30 * $ratio;
                        if ($info['sex'] == 1) $love += 30 * $ratio;
//                        $lucky += 0;
                        $money += 40 * $ratio;
//                        $study += 0;
//                        $health += 0;
                        $home += 40 * $ratio;
//                        $travle += 0;
                        $chat += 10 * $ratio;
                    } elseif ($i == 2) {
                        $work += 60 * $ratio;
//                        if ($info['sex'] != 1) $love += 0;
//                        $lucky += 0;
//                        $money += 0;
                        $study += 80 * $ratio;
//                        $health += 0;
//                        $home += 0;
                        $travle += 60 * $ratio;
                        $chat += 30 * $ratio;
                    } elseif ($i == 3) {
                        $work += 100 * $ratio;
                        $love += 80 * $ratio;
                        $lucky += 30 * $ratio;
                        $money += 90 * $ratio;
//                        $study += 0;
//                        $health += 0;
//                        $home += 0;
                        $travle += 50 * $ratio;
                        $chat += 100 * $ratio;
                    } elseif ($i == 4) {
                        $work -= 30 * $ratio;
//                        $love += 0;
                        $lucky -= 40 * $ratio;
//                        $money += 0;
//                        $study += 0;
//                        $health += 0;
//                        $home += 0;
                        $travle -= 30 * $ratio;
                        $chat -= 20 * $ratio;
                    } elseif ($i == 5) {
                        $work += 120 * $ratio;
//                        $love += 0;
                        $lucky += 120 * $ratio;
                        $money += 50 * $ratio;
                        $study += 60 * $ratio;
//                        $health += 0;
//                        $home += 0;
                        $travle += 100 * $ratio;
                        $chat += 50 * $ratio;
                    } elseif ($i == 6) {
                        $work -= 30 * $ratio;
//                        $love += 0;
                        $lucky -= 40 * $ratio;
//                        $money += 0;
//                        $study += 0;
//                        $health += 0;
//                        $home += 0;
                        $travle -= 30 * $ratio;
                        $chat -= 20 * $ratio;
                    } elseif ($i == 7) {
//                        $work += 0;
                        $love -= 50 * $ratio;
//                        $lucky += 0;
//                        $money += 0;
                        $study += 30 * $ratio;
//                        $health += 0;
                        $home -= 30 * $ratio;
//                        $travle += 0;
                        $chat -= 20 * $ratio;
                    } elseif ($i == 8) {
                        $work -= 30 * $ratio;
//                        $love += 0;
                        $lucky -= 40 * $ratio;
//                        $money += 0;
//                        $study += 0;
//                        $health += 0;
//                        $home += 0;
                        $travle -= 30 * $ratio;
                        $chat -= 20 * $ratio;
                    } elseif ($i == 9) {
                        $work -= 30 * $ratio;
//                        $love += 0;
                        $lucky -= 40 * $ratio;
//                        $money += 0;
//                        $study += 0;
//                        $health += 0;
//                        $home += 0;
                        $travle -= 30 * $ratio;
                        $chat -= 20 * $ratio;
                    } elseif ($i == 12) {
                        $work += 50 * $ratio;
                        $love -= 10 * $ratio;
                        $lucky += 30 * $ratio;
                        $money += 30 * $ratio;
//                        $study += 0;
//                        $health += 0;
                        $home -= 10 * $ratio;
//                        $travle += 0;
//                        $chat += 0;
                    }

                    $influ[$i][1] = $ratio;
                }

                if ($ld[2] < 1) {

                    $ratio = (1 - $ld[2]) / 2;

                    if ($i == 0) {
                        $work += 50 * $ratio;
                        if ($info['sex'] != 1) $love += 100 * $ratio;
                        else $love += 60 * $ratio;
                        $lucky += 30 * $ratio;
//                        $money += 0;
//                        $study += 0;
                        $health += 30 * $ratio;
//                        $home += 0;
                        $travle += 10 * $ratio;
                        $chat += 100 * $ratio;
                    } elseif ($i == 1) {
//                        $work += 0;
                        if ($info['sex'] != 1) $love += 60 * $ratio;
                        else $love += 100 * $ratio;
//                        $lucky += 0;
                        $money += 20 * $ratio;
//                        $study += 0;
//                        $health += 0;
                        $home += 40 * $ratio;
//                        $travle += 0;
                        $chat += 50 * $ratio;
                    } elseif ($i == 2) {
//                        $work += 0;
                        $love += 40 * $ratio;
//                        $lucky += 0;
//                        $money += 0;
                        $study += 50 * $ratio;
//                        $health += 0;
//                        $home += 0;
                        $travle += 30 * $ratio;
                        $chat += 70 * $ratio;
                    } elseif ($i == 3) {
//                        $work += 0;
                        $love += 120 * $ratio;
                        $lucky += 20 * $ratio;
                        $money += 50 * $ratio;
//                        $study += 0;
//                        $health += 0;
//                        $home += 0;
                        $travle += 40 * $ratio;
                        $chat += 120 * $ratio;
                    } elseif ($i == 4) {
//                        $work += 0;
                        if ($info['sex'] != 1) $love += 30 * $ratio;
                        else $love -= 30 * $ratio;
                        $lucky -= 30 * $ratio;
//                        $money += 0;
//                        $study += 0;
                        $health -= 20 * $ratio;
//                        $home += 0;
                        $travle -= 30 * $ratio;
                        $chat -= 60 * $ratio;
                    } elseif ($i == 5) {
                        $work += 60 * $ratio;
                        $love += 100 * $ratio;
                        $lucky += 80 * $ratio;
                        $money += 30 * $ratio;
                        $study += 40 * $ratio;
//                        $health += 0;
//                        $home += 0;
                        $travle += 80 * $ratio;
                        $chat += 100 * $ratio;
                    } elseif ($i == 6) {
//                        $work += 0;
                        $love -= 30 * $ratio;
                        $lucky -= 30 * $ratio;
//                        $money += 0;
//                        $study += 0;
                        $health -= 20 * $ratio;
//                        $home += 0;
                        $travle -= 30 * $ratio;
                        $chat -= 60 * $ratio;
                    } elseif ($i == 7) {
//                        $work += 0;
                        $love -= 100 * $ratio;
//                        $lucky += 0;
//                        $money += 0;
                        $study += 20 * $ratio;
//                        $health += 0;
                        $home -= 30 * $ratio;
//                        $travle += 0;
                        $chat -= 40 * $ratio;
                    } elseif ($i == 8) {
//                        $work += 0;
                        $love -= 50 * $ratio;
                        $lucky -= 30 * $ratio;
//                        $money += 0;
//                        $study += 0;
                        $health -= 20 * $ratio;
//                        $home += 0;
                        $travle -= 30 * $ratio;
                        $chat -= 60 * $ratio;
                    } elseif ($i == 9) {
//                        $work += 0;
                        $love -= 50 * $ratio;
                        $lucky -= 30 * $ratio;
//                        $money += 0;
//                        $study += 0;
                        $health -= 20 * $ratio;
//                        $home += 0;
                        $travle -= 30 * $ratio;
                        $chat -= 60 * $ratio;
                    } elseif ($i == 12) {
                        $work -= 20 * $ratio;
                        $love += 50 * $ratio;
                        $lucky -= 10 * $ratio;
                        $money -= 10 * $ratio;
//                        $study += 0;
                        $health -= 20 * $ratio;
//                        $home += 0;
//                        $travle += 0;
                        $chat += 50 * $ratio;
                    }

                    $influ[$i][2] = $ratio;
                }

                if ($ld[3] < 1) {

                    $ratio = (1 - $ld[3]) / 2;

                    if ($i == 0) {
                        $work += 30;
                        if ($info['sex'] != 1) $love += 30;
                        $lucky += 30 * $ratio;
//                        $money += 0;
//                        $study += 0;
                        $health += 40 * $ratio;
                        $home += 80 * $ratio;
                        $travle += 10 * $ratio;
                        $chat += 20 * $ratio;
                    } elseif ($i == 1) {
//                        $work += 0;
                        if ($info['sex'] == 1) $love += 30 * $ratio;
//                        $lucky += 0;
                        $money += 30 * $ratio;
//                        $study += 0;
//                        $health += 0;
                        $home += 100 * $ratio;
//                        $travle += 0;
                        $chat += 10 * $ratio;
                    } elseif ($i == 2) {
//                        $work += 0;
//                        $love += 0;
//                        $lucky += 0;
//                        $money += 0;
                        $study += 40 * $ratio;
//                        $health += 0;
                        $home += 20 * $ratio;
                        $travle += 30 * $ratio;
//                        $chat += 0;
                    } elseif ($i == 3) {
//                        $work += 0;
                        $love += 70 * $ratio;
                        $lucky += 10 * $ratio;
                        $money += 50 * $ratio;
//                        $study += 0;
//                        $health += 0;
                        $home += 90 * $ratio;
                        $travle += 20 * $ratio;
                        $chat += 40 * $ratio;
                    } elseif ($i == 4) {
                        $work -= 20 * $ratio;
//                        $love += 0;
                        $lucky -= 30 * $ratio;
//                        $money += 0;
//                        $study += 0;
//                        $health += 0;
                        $home -= 70 * $ratio;
                        $travle -= 30 * $ratio;
                        $chat -= 20 * $ratio;
                    } elseif ($i == 5) {
                        $work += 60 * $ratio;
//                        $love += 0;
                        $lucky += 80 * $ratio;
                        $money += 40 * $ratio;
                        $study += 20 * $ratio;
//                        $health += 0;
                        $home += 80 * $ratio;
                        $travle += 60 * $ratio;
//                        $chat += 0;
                    } elseif ($i == 6) {
                        $work -= 20 * $ratio;
//                        $love += 0;
                        $lucky -= 30 * $ratio;
//                        $money += 0;
//                        $study += 0;
//                        $health += 0;
                        $home -= 40 * $ratio;
                        $travle -= 30 * $ratio;
                        $chat -= 20 * $ratio;
                    } elseif ($i == 7) {
//                        $work += 0;
                        $love -= 50 * $ratio;
//                        $lucky += 0;
//                        $money += 0;
                        $study += 10 * $ratio;
//                        $health += 0;
                        $home -= 60 * $ratio;
//                        $travle += 0;
                        $chat -= 20 * $ratio;
                    } elseif ($i == 8) {
                        $work -= 20 * $ratio;
//                        $love += 0;
                        $lucky -= 30 * $ratio;
//                        $money += 0;
//                        $study += 0;
//                        $health += 0;
                        $home -= 40 * $ratio;
                        $travle -= 30 * $ratio;
                        $chat -= 20 * $ratio;
                    } elseif ($i == 9) {
                        $work -= 20 * $ratio;
//                        $love += 0;
                        $lucky -= 30 * $ratio;
//                        $money += 0;
//                        $study += 0;
//                        $health += 0;
                        $home -= 40 * $ratio;
                        $travle -= 30 * $ratio;
                        $chat -= 20 * $ratio;
                    } elseif ($i == 12) {
                        $work -= 20 * $ratio;
                        $love += 30 * $ratio;
                        $lucky -= 10 * $ratio;
                        $money -= 10 * $ratio;
//                        $study += 0;
//                        $health += 0;
                        $home += 30 * $ratio;
//                        $travle += 0;
//                        $chat += 0;
                    }

                    $influ[$i][3] = $ratio;
                }
            }
        }
        // 在最强能量点的1经纬度内
        if ($multiple > 1) {
            $work *= $multiple;
            $love *= $multiple;
            $lucky *= $multiple;
            $money *= $multiple;
            $study *= $multiple;
            $health *= $multiple;
            $home *= $multiple;
            $travle *= $multiple;
            $chat *= $multiple;
        }


        // 修正：如某地点 工作是正的，财富是负的，财富最终值=财富值+工作值 20181106
        if ($work > 0 && $money < 0) $money = $money + $work;

        if (isset($info['fate']) && $info['fate']) {
            //0养生 1工作 2学习 3旅游 4定居 5婚恋 6财富 7社交 8幸运
            return [
                0 => $health,
                1 => $work,
                2 => $study,
                3 => $travle,
                4 => $home,
                5 => $love,
                6 => $money,
                7 => $chat,
                8 => $lucky,
            ];
        } else {
            $good = '#13d08d';
            $bad = '#ff9400';

            $money = round($money);
            $work = round($work);
            $love = round($love);
            $health = round($health);
            $study = round($study);
            $lucky = round($lucky);

            $change_list = [
                0 => [
                    'name' => '财富',
                    'percent' => $money >= 0 ? '+' . abs($money) . '%' : $money . '%',
                    'color' => $money >= 0 ? $good : $bad,
                ],
                1 => [
                    'name' => '工作',
                    'percent' => $work >= 0 ? '+' . abs($work) . '%' : $work . '%',
                    'color' => $work >= 0 ? $good : $bad,
                ],
                2 => [
                    'name' => '婚恋',
                    'percent' => $love >= 0 ? '+' . abs($love) . '%' : $love . '%',
                    'color' => $love >= 0 ? $good : $bad,
                ],
                3 => [
                    'name' => '健康',
                    'percent' => $health >= 0 ? '+' . abs($health) . '%' : $health . '%',
                    'color' => $health >= 0 ? $good : $bad,
                ],
                4 => [
                    'name' => '学习',
                    'percent' => $study >= 0 ? '+' . abs($study) . '%' : $study . '%',
                    'color' => $study >= 0 ? $good : $bad,
                ],
                5 => [
                    'name' => '幸运',
                    'percent' => $lucky >= 0 ? '+' . abs($lucky) . '%' : $lucky . '%',
                    'color' => $lucky >= 0 ? $good : $bad,
                ],
            ];

            $travle_recommend = ($travle / 2);
            $work_recommend = ($work / 2);
            $love_recommend = ($love / 2);
            $health_recommend = ($health / 2);
            $study_recommend = ($study / 2);
            $home_recommend = ($home / 2);
            //工作对应工作，婚恋对应婚恋，旅游对应旅游，学习对应学习，养生对应健康
            $recommend = [
                0 => [
                    'name' => '养生',
                    'score' => round(Mod100($health_recommend)),
                    'status' => $this->getRecommendText($health_recommend),
                    'icon' => config('map.map')['yangcheng_recommend']
                ],
                1 => [
                    'name' => '工作',
                    'score' => round(Mod100($work_recommend)),
                    'status' => $this->getRecommendText($work_recommend),
                    'icon' => config('map.map')['work_recommend']
                ],
                2 => [
                    'name' => '学习',
                    'score' => round(Mod100($study_recommend)),
                    'status' => $this->getRecommendText($study_recommend),
                    'icon' => config('map.map')['study_recommend']
                ],
                3 => [
                    'name' => '旅游',
                    'score' => round(Mod100($travle_recommend)),
                    'status' => $this->getRecommendText($travle_recommend),
                    'icon' => config('map.map')['trip_recommend']
                ],
                4 => [
                    'name' => '定居',
                    'score' => round(Mod100($home_recommend)),
                    'status' => $this->getRecommendText($home_recommend),
                    'icon' => config('map.map')['dingju_recommend']
                ],
                5 => [
                    'name' => '婚恋',
                    'score' => round(Mod100($love_recommend)),
                    'status' => $this->getRecommendText($love_recommend),
                    'icon' => config('map.map')['love_recommend']
                ]
            ];

            $recommend = resort($recommend, 'score');// 排序


            // 获取用户的命运之城的信息 TODO 添加缓存封装
            $where = ['fu.rid' => $info['rid'], 'm.longitude' => sprintf('%.6f', $info['point_longitude']), 'm.latitude' => sprintf('%.6f', $info['point_latitude'])];
            $fate_info = DB::table('app_map')->alias('m')
                ->field('fu.fcid')
                ->join('app_fate_city_user fu', 'm.id=fu.mid', 'LEFT')
                ->where($where)
                ->select();
            $explain_list = [];
            if (!empty($fate_info)) {
                foreach ($fate_info as $k => $v) {
                    $explain_list[] = [
                        'name' => config('map.fate_city_name')[$v['fcid']],
                        'icon' => config('map.fate_city')[$v['fcid']],
                        'description' => config('map.fate_city_des')[$v['fcid']]
                    ];
                }
                $type = true;
            } else {
                $type = false;
            }

            if (empty($explain_list)) {
                // 若在某线影响范围内
                if (!empty($influ)) {
                    $lines_icon = config('map.lines_icon');
                    $lines_name = config('map.lines_name');// 线的名称
                    $lines_id = ['Ⅰ', 'Ⅱ', 'Ⅲ', 'Ⅳ'];

                    $lids = [7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 12 => 17];
                    foreach ($influ as $k => $inf) {
                        foreach ($inf as $iv => $in) {
                            $lid = $lids[$k];
                            if (isset($lines_icon[$lid]))
                                $explain_list[] = [
                                    'icon' => $lines_icon[$lid],
                                    'description' => '位于' . $lines_name[$lid] . $lines_id[$iv] . '的影响范围内，受影响指数' . round($in * 100) . '%',
                                ];
                        }

                    }
                }
            }

            $result = [
                'name' => '石家庄',
                'allowedness' => 15,
                'allowed_color' => '#000000',
                'distance' => '100km',
                'score_list' => $change_list,
                'explain_list' => $explain_list,
                'recommend_list' => $recommend,
                'type' => $type
            ];

            return $result;
        }
    }

    /**
     * 星体影响力
     * @param null $pid
     * @param array $data
     * @return float|int
     */
    protected function getPlanetInfluence($pid = null, $data = [])
    {
        $planet = $data['planets'][$pid];

        $base_axis = 16;

        $planet_in_house = $planet['in_house_id'];

        // 合轴-上升 100
        if (isset($planet['phase'][$pid . '-' . ASC]) && $planet['phase'][$pid . '-' . ASC]['phase_e'] == 0) {
            $phase_orb = $planet['phase'][$pid . '-' . ASC]['phase_orb'];

            $coe = (1 - $phase_orb / $base_axis);

            $result = 100 * $coe;

            if ($planet_in_house % 3 != 0) $result *= $coe;

            $result = $result / 2;// 加上命格线影响，合轴影响力折半
            // 合轴-天底 70
        } elseif (isset($planet['phase'][$pid . '-' . IC]) && $planet['phase'][$pid . '-' . IC]['phase_e'] == 0) {
            $phase_orb = $planet['phase'][$pid . '-' . IC]['phase_orb'];

            $coe = (1 - $phase_orb / $base_axis);

            $result = 70 * $coe;

            if ($planet_in_house % 3 != 0) $result *= $coe;

            $result = $result / 2;// 加上命格线影响，合轴影响力折半
            // 合轴-下降 80
        } elseif (isset($planet['phase'][$pid . '-' . DES]) && $planet['phase'][$pid . '-' . DES]['phase_e'] == 0) {
            $phase_orb = $planet['phase'][$pid . '-' . DES]['phase_orb'];

            $coe = (1 - $phase_orb / $base_axis);

            $result = 80 * $coe;

            if ($planet_in_house % 3 != 0) $result *= $coe;

            $result = $result / 2;// 加上命格线影响，合轴影响力折半
            // 合轴-天顶 90
        } elseif (isset($planet['phase'][$pid . '-' . MC]) && $planet['phase'][$pid . '-' . MC]['phase_e'] == 0) {
            $phase_orb = $planet['phase'][$pid . '-' . MC]['phase_orb'];

            $coe = (1 - $phase_orb / $base_axis);

            $result = 90 * $coe;

            if ($planet_in_house % 3 != 0) $result *= $coe;

            $result = $result / 2;// 加上命格线影响，合轴影响力折半
        } else {
            $regular = [
                1 => 1, 2 => 1, 3 => 1,
                4 => 4, 5 => 4, 6 => 4,
                7 => 7, 8 => 7, 9 => 7,
                10 => 10, 11 => 10, 12 => 10,
            ];

            $quadrant_base1 = [1 => 50, 4 => 35, 7 => 40, 10 => 10];
            $quadrant_base2 = [1 => 120, 4 => 150, 7 => 130, 10 => 140];

            $in_quadrant = $regular[$planet_in_house];// 位于象限

            $axis_distance = abs($planet['deg'] - $data['planets'][ASC]['deg']);
            if ($axis_distance > 180) $axis_distance = 360 - $axis_distance;

            $result = $quadrant_base1[$in_quadrant] * (1 - ($axis_distance - 8) / $quadrant_base2[$in_quadrant]);
        }

        return $result;
    }

    /**
     * 宫位分数变化
     * @param int $house
     * @param array $data
     * @param int $base
     * @return float|int
     */
    protected function changeByHousePower($house = 1, $data = [], $base = 1)
    {
        $house_power = $data['house_score'][$house - 1]['lucky'] - $data['house_score'][$house - 1]['burn'];

        $result = $house_power / $base;

        return $result;
    }

    /**
     * 获取位置推荐文字
     * @param int $score
     * @return string
     */
    protected function getRecommendText($score = 0)
    {
        if ($score <= 0) $text = '不适宜';
        elseif ($score < 20) $text = '适宜';
        elseif ($score < 40) $text = '较好';
        elseif ($score < 60) $text = '良好';
        elseif ($score < 80) $text = '力荐';
        else $text = '绝佳';
        return $text;
    }


    /**
     * @param array $info
     * @return array
     * @throws ApiException
     */
    public function getDrawLineInfo($info = [])
    {
        if (empty($info)) throw new ApiException('档案信息错误', 200, config('code.error'));

        $utdatenow = strftime("%d.%m.%Y", $info['time']);

        $utnow = strftime("%H:%M:%S", $info['time']);

        $longitude = $info['longitude'];// 用户经度

        $latitude = $info['latitude'];// 用户纬度

        $point_longitude = $info['point_longitude'];

        $point_latitude = $info['point_latitude'];

        $exec_str = config('astrolog.prefix') . " -b{$utdatenow} -ut{$utnow} -p0123456789DAmHt -eswe -house{$longitude},{$latitude},p -fad -g, -head";

        exec($exec_str, $out);

        if (empty($out) || count($out) < 27) {

            unset($out);

            $exec_str = config('astrolog.prefix') . " -b{$utdatenow} -ut{$utnow} -p0123456789DAmHt -eswe -house{$longitude},{$latitude},w -fad -g, -head";

            exec($exec_str, $out);
        }

        $planet1 = $planet2 = [];

        foreach ($out as $k => $o) {

            if ($k <= 9 || $k == 12 || $k == 27 || $k == 28) {

                $line = explode(',', $o);

                $key = $k;

                if ($k == 27) $key = 17;

                if ($k == 28) $key = 20;

                $planet1[$key] = $line[0] * 1;

                $planet2[$key] = $line[1] * 1;
            }
        }

        $longm = $this->Mod180($planet1[MC] - $longitude); // 天顶的赤经 - 用户经度

        $degToRadian = 180 / M_PI; // 角度转弧度

        // 获取用户当前已解锁的命格线 string 12位
        $lines = (new MapRecode())->getRecodeUnlockLines(['rid' => $info['rid'], 'uid' => $info['uid'], 'isself' => $info['isself']]);

        $temp = [];

        $temp['near_power'] = 1;// *1表示不在能量最强的点附近 *2表示位于1个点附近 *4表示位于两个点附近 以此类推

        for ($i = 0; $i < ASC; $i++) {
            if (!isset($planet1[$i]) || ($i < 10 && $lines[$i] == 0) || ($i == 12 && $lines[10] == 0)) continue;

            $diff_x3 = $diff_x4 = 9999;// 由于上升下降在两极范围无值 设置默认值

            $x1 = $this->Mod180($planet1[$i] + $longitude - $planet1[MC]);// 天顶

            $max_power = [$x1, $planet2[$i]];// 能量最强的点

            $x2 = $this->Mod180($x1 + 180); // 天底

            $ad = asin(tan($planet2[$i] / $degToRadian) * tan($point_latitude / $degToRadian));

            $x3 = $this->Mod180($planet1[$i] - $ad * $degToRadian - 90 - $longm);// 上升

            $x4 = $this->Mod180($planet1[$i] + $ad * $degToRadian + 90 - $longm);// 下降

            $diff_x1 = abs($point_longitude - $x1);

            $diff_x2 = abs($point_longitude - $x2);

            if (!is_nan($x3)) $diff_x3 = abs($point_longitude - $x3);

            if (!is_nan($x4)) $diff_x4 = abs($point_longitude - $x4);
            // 上升 - 天顶 - 下降 - 天底 顺序存储
            $temp[$i][0] = $diff_x3;//if ($diff_x3 <= 1)

            $temp[$i][1] = $diff_x1;//if ($diff_x1 <= 1)

            $temp[$i][2] = $diff_x4;//if ($diff_x4 <= 1)

            $temp[$i][3] = $diff_x2;//if ($diff_x2 <= 1)

            // 判断当前点是否位于能量最强的点经度1纬度1以内 若是，则计算的结果*2
            if ((abs($point_longitude - $max_power[0]) < 1 || abs($point_longitude + $max_power[0]) < 1)
                && abs($point_latitude - $max_power[1]) < 1) $temp['near_power'] *= 2;
        }
        return $temp;
    }

    public function Mod180($d)
    {
        $d -= floor($d / 360) * 360;

        if ($d >= 180) $d -= 360;

        else if ($d < -180) $d += 360;

        return $d;
    }
}
